package com.ctrlspace.core.managers;

import com.ctrlspace.core.dao.UserDao;
import com.ctrlspace.core.util.Security;
import com.ctrlspace.model.User;

public class UserManager {
    private static UserManager _instance;
    private final UserDao dao = new UserDao();
    
    private UserManager() {}

    public static UserManager getInstance() {
            if (_instance == null) {
                    _instance = new UserManager();
            }
            
            return _instance;
    }

    public User createUser(String username, String password, String email,
                    String firstName, String lastName) {
            
            User newUser = null;
            
            // Check first if user name is taken
            boolean userExists = dao.userExists(username);
            if (userExists) {
                    // TODO: Add custom exception (?) or just return null
                    return newUser;
            }
            
            // Hash password
            String hashedPassword = null;
            hashedPassword = Security.SHA1(password);
            
            newUser = dao.createUser(username, hashedPassword, email, firstName, lastName);
            
            return newUser;
    }
    
    public User getUser(int id) {
    	return dao.getUser(id);
    }

	public void updateUser(User user) {
        dao.updateUser(user.getId(), user.getUsername(), user.getEmail(), user.getFirstName(), user.getLastName(), user.getLastLogin(), user.getLastIp());
	}

	public User getUser(String username, String password) {
		String hashedPassword = Security.SHA1(password);
		return dao.getUserFromCredentials(username, hashedPassword);
	}

}